#include "hithread.h"
#include <string.h>

void *HiThread::run(void *arg)
{
    HiThread *thread = static_cast<HiThread *>(arg);
    thread->process();
    pthread_exit(NULL);
}

HiThread::HiThread()
{
    pthread_attr_setdetachstate(&tattr_, PTHREAD_CREATE_JOINABLE);
    pthread_attr_init(&tattr_);
    thread_    = 0;
    stop_     = false;
    running_   = false;
}

HiThread::~HiThread()
{
    pthread_mutex_destroy(&lock_);
    pthread_attr_destroy(&tattr_);
}

bool HiThread::start(char *threadname)
{
    strncpy(thread_name_, threadname, sizeof(thread_name_));
    if(running_)
    {
        //hi_verbose("%s - Thread already running\n", m_threadName);
        return false;
    }

    stop_    = false;
    running_ = true;

    pthread_create(&thread_, &tattr_, &HiThread::run, this);

   // hi_verbose("%s - Thread with id %d started\n", m_threadName, (int)m_thread);
    return true;
}

bool HiThread::running()
{
    return running_;
}

pthread_t HiThread::thread_handle()
{
    return thread_;
}

bool HiThread::stop_thread()
{
    if(!running_)
    {
       // hi_verbose("%s - No thread running", m_threadName);
        return false;
    }

    stop_ = true;
    pthread_join(thread_, NULL);
    running_ = false;

    thread_ = 0;

  //  hi_verbose("%s - Thread stopped\n", m_threadName);
    return true;
}
